const Producttype = require('../models/producttype.model');

// 新
exports.create = function(req, res, next) {
  const producttype = new Producttype(req.body);
  producttype.save().then(data => {
    res.json(data);
  });
};

exports.remove = function(req, res, next) {
  var id = req.params.id;
  Producttype.findByIdAndDelete(id, (err, data) => {
    res.json(data);
  });
};


// 改
exports.update = function(req, res, next) {
  var id = req.params.id;
  Producttype.findByIdAndUpdate(id, { $set: req.body }, { new: false }).then(data => {
    // 千万小心，这里的data是没有更新之前的数据
    res.json(data);
  });
};

exports.getData = function(req, res, next) {
  var id = req.params.id;
  Producttype.findById(id).then(data => {
    res.json(data);
  });
};

exports.list = function(req, res, next) {
  var page = req.body.page ? req.body.page : 1;
  var rows = req.body.rows ? req.body.rows : 10;

  var queryCondition = {};

  if (req.body.name) {
    name = req.body.name;
    queryCondition = {
      name: new RegExp(name, 'i')
    };
  }

  Producttype.paginate(queryCondition, { page: +page, limit: +rows }, function(err, result) {
    result.rows = result.docs;
    delete result.docs;
    res.json(result);
  });
};
exports.list1 = function(req, res, next) {
  var page = req.body.page ? req.body.page : 1;
  var rows = req.body.rows ? req.body.rows : 10;

  var ids=req.body.ids.split(',');
  console.log(ids)
    Producttype.paginate({parentId : {$in : ids}}, { page: +page, limit: +rows }, function(err, result) {
        console.log(result);
        result.rows = result.docs;
        delete result.docs;
        console.log(result);
        res.json(result);
      });
};
